<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1100px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="仓库" prop="warehouseId">
            <el-select
              v-model="formData.warehouseId"
              placeholder="请输入仓库"
              :clearable="true"
              :disabled="isEdit || isShow"
            >
              <el-option
                v-for="dict in materialWarehouse"
                :key="dict.id"
                :label="dict.warehouseName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库人" prop="stockInClerkId">
            <el-select
              v-model="formData.stockInClerkId"
              placeholder="请输入入库人"
              :disabled="isShow"
            >
              <el-option
                v-for="dict in userList"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="来源类型" prop="sourceType">
            <el-select
              v-model="formData.sourceType"
              placeholder="请输入来源类型"
              :disabled="isEdit || isShow"
              @change="handleChangeSourceType"
            >
              <el-option
                v-for="dict in sourceType"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="来源单据编号" prop="sourceNo">
            <el-input v-model="formData.sourceNo" disabled class="!w-160px" />
          </el-form-item>
        </el-col>
        <el-col :span="2" :pull="3">
          <el-button
            @click="handleClickSelectOrder"
            :style="{ display: isShow ? 'none' : 'block' }"
          >
            选择单据
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              placeholder="请输入备注"
              type="textarea"
              :clearable="true"
              :disabled="isShow"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item :style="{ display: isShow ? 'none' : 'block' }">
      <el-button @click="clickAddMaterial">添加物资</el-button>
      <el-button @click="clickDeleteMaterial">删除物资</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      height="400"
      :data="formData.details"
      save-key="MaterialStockInEdit"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    >
      <template #number="{ row }">
        <InputNumber v-model="row.number" class="!w-85px" type="decimal" :disabled="isShow" />
      </template>
      <template #batchNo="{ row }">
        <el-input v-model="row.batchNo" :disabled="isShow" class="!w-100px" />
      </template>
      <template #productionDate="{ row }">
        <el-date-picker
          v-model="row.productionDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 130px !important"
          :disabled="isShow"
        />
      </template>
      <template #expireDate="{ row }">
        <el-date-picker
          v-model="row.expireDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 130px !important"
          :disabled="isShow"
        />
      </template>
      <template #remark="{ row }">
        <el-input v-model="row.remark" :disabled="isShow" />
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <MaterialInfoSelect ref="materialInfoSelectRef" @select-value="handleSelectMaterialInfo" />
  <MaterialPurchaseSelect
    ref="materialPurchaseSelectRef"
    @select-value="handleSelectMaterialOrder"
  />
  <MaterialTransferSelect
    ref="materialTransferSelectRef"
    @select-value="handleSelectMaterialOrder"
  />
</template>
<script setup name="MaterialStockInEdit" lang="ts">
import * as MaterialStockInApi from '@/api/material/stockIn'
import * as MaterialWarehouseApi from '@/api/material/warehouse'
import * as UserApi from '@/api/system/user/user'
import { DICT_TYPE, getIntDictOptions, DictDataType } from '@/utils/dict'
import MaterialInfoSelect from '../materialInfo/MaterialInfoSelect.vue'
import MaterialPurchaseSelect from '../materialPurchase/MaterialPurchaseSelect.vue'
import MaterialTransferSelect from '../materialTransfer/MaterialTransferSelect.vue'
import * as MaterialStockInModel from '@/model/material/stock/MaterialStockIn'
import * as MaterialStockInDetailModel from '@/model/material/stock/MaterialStockInDetail'
import {
  MaterialStockInStatusEnum,
  MaterialStockInSourceTypeEnum,
  MaterialPurchaseStatusEnum,
  MaterialTransferStatusEnum
} from '@/utils/constants'
import InputNumber from '@/components/InputNumber/src/InputNumber.vue'
interface MaterialStockInDetailEdit extends MaterialStockInDetailModel.MaterialStockInDetail {
  'material.materialName': string
  'material.category.categoryName': string
  'material.price': string
  'material.materialSpecification': string
  expectNumber: string
  operateType: string
}

interface MaterialStockInEdit extends MaterialStockInModel.MaterialStockIn {
  details: MaterialStockInDetailEdit[]
}

const materialInfoSelectRef = ref()
const materialPurchaseSelectRef = ref()
const materialTransferSelectRef = ref()
const userList = ref()
let formType = ''
const message = useMessage()
const { t } = useI18n()
const materialWarehouse = ref()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const isEdit = ref(false)
const isShow = ref(false)
const isOrder = ref(false)
const sourceType = ref<DictDataType[]>([])
const formData = ref<MaterialStockInEdit>({
  id: undefined,
  stockInNo: '',
  warehouseId: undefined,
  sourceType: 1,
  sourceId: 0,
  status: 0,
  remark: '',
  stockInClerkId: undefined,
  sourceNo: '',
  details: []
})
const formRules = reactive({
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'change' }],
  stockInClerkId: [{ required: true, message: '入库人不能为空', trigger: 'change' }],
  sourceType: [{ required: true, message: '来源类型不能为空', trigger: 'change' }]
})
const tableCurrentRow = ref<MaterialStockInDetailEdit>()
const columns = [
  {
    label: '物资名称',
    prop: 'material.materialName'
  },
  {
    label: '物资类别名称',
    prop: 'material.category.categoryName'
  },
  {
    label: '物资规格',
    prop: 'material.materialSpecification'
  },
  {
    label: '销售单价',
    prop: 'material.price'
  },
  {
    label: '预期数量',
    prop: 'expectNumber'
  },
  {
    label: '数量',
    prop: 'number',
    slot: 'number',
    minWidth: '85'
  },
  {
    label: '批次号',
    prop: 'batchNo',
    slot: 'batchNo',
    minWidth: '115'
  },
  {
    label: '生产日期',
    prop: 'productionDate',
    slot: 'productionDate',
    minWidth: '140'
  },
  {
    label: '有效期',
    prop: 'expireDate',
    slot: 'expireDate',
    minWidth: '140'
  },
  {
    label: '备注',
    prop: 'remark',
    slot: 'remark'
  }
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  materialWarehouse.value = await MaterialWarehouseApi.simpleList()
  userList.value = await UserApi.listAllSimple()
  sourceType.value = getIntDictOptions(DICT_TYPE.MATERIAL_STOCK_IN_SOURCE_TYPE)
  sourceType.value = sourceType.value.filter(
    (item) => item.value != MaterialStockInSourceTypeEnum.INVENTORY
  )
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    isEdit.value = true
    try {
      formData.value = await MaterialStockInApi.singleGet(id)
      if (formData.value.status != MaterialStockInStatusEnum.PENDING_REVIEW) {
        isShow.value = true
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaterialStockInEdit
    if (formType === 'create') {
      await MaterialStockInApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaterialStockInApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  isShow.value = false
  isEdit.value = false
  formData.value = {
    id: undefined,
    stockInNo: '',
    warehouseId: undefined,
    sourceType: 1,
    sourceId: 0,
    status: 0,
    remark: '',
    stockInClerkId: undefined,
    sourceNo: '',
    details: []
  }
  formRef.value?.resetFields()
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row: MaterialStockInDetailEdit | undefined) => {
  tableCurrentRow.value = row
}

const clickAddMaterial = () => {
  materialInfoSelectRef.value.open()
}

const handleClickSelectOrder = () => {
  if (formData.value.sourceType == MaterialStockInSourceTypeEnum.PURCHASE) {
    materialPurchaseSelectRef.value.open({
      status: {
        value: [MaterialPurchaseStatusEnum.PENDING_IN, MaterialPurchaseStatusEnum.PARTIAL_IN],
        isDisabled: true
      }
    })
  }
  if (formData.value.sourceType == MaterialStockInSourceTypeEnum.TRANSFER) {
    materialTransferSelectRef.value.open({
      status: {
        value: [MaterialTransferStatusEnum.PENDING_IN, MaterialTransferStatusEnum.PARTIAL_IN],
        isDisabled: true
      }
    })
  }
}

const clickDeleteMaterial = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的物资')
    return
  }
  if (formType === 'create' || tableCurrentRow.value.id == undefined) {
    const index = formData.value.details.indexOf(tableCurrentRow.value)
    formData.value.details.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
}

const handleChangeSourceType = (type) => {
  if (
    [MaterialStockInSourceTypeEnum.PURCHASE, MaterialStockInSourceTypeEnum.TRANSFER].includes(type)
  ) {
    isOrder.value = true
    formData.value.warehouseId = undefined
  } else {
    isOrder.value = false
    formData.value.sourceId = 0
    formData.value.sourceNo = ''
  }
  formData.value.details = []
}

const handleSelectMaterialInfo = (selectMaterialInfoList) => {
  selectMaterialInfoList.forEach((element) => {
    const detail = {
      id: undefined,
      stockInId: formType === 'create' ? undefined : formData.value.id,
      materialId: element.id,
      'material.materialName': element.materialName,
      'material.category.categoryName': element.category.categoryName,
      'material.price': element.price,
      'material.materialSpecification': element.materialSpecification,
      number: 1,
      expectNumber: '',
      batchNo: '',
      productionDate: '',
      expireDate: '',
      remark: '',
      operateType: 'new'
    }
    formData.value.details.push(detail)
  })
}

const handleSelectMaterialOrder = (selectMaterialOrder) => {
  formData.value.details = []
  formData.value.sourceNo =
    MaterialStockInSourceTypeEnum.PURCHASE == formData.value.sourceType
      ? selectMaterialOrder['order'].purchaseNo
      : selectMaterialOrder['order'].transferNo
  formData.value.sourceId = selectMaterialOrder['order'].id
  formData.value.warehouseId =
    MaterialStockInSourceTypeEnum.PURCHASE == formData.value.sourceType
      ? selectMaterialOrder['order'].warehouseId
      : selectMaterialOrder['order'].inWarehouseId
  selectMaterialOrder['details'].forEach((element) => {
    const detail = {
      id: undefined,
      stockInId: formType === 'create' ? undefined : formData.value.id,
      materialId: element.materialId,
      'material.materialName': element.material.materialName,
      'material.category.categoryName': element.material.category.categoryName,
      'material.price': element.material.price,
      'material.materialSpecification': element.material.materialSpecification,
      number: 1,
      expectNumber: Math.max(element.number - element.inNumber, 0).toString(),
      batchNo: element.batchNo,
      productionDate: element.productionDate,
      expireDate: element.expireDate,
      remark: '',
      operateType: 'new'
    }
    formData.value.details.push(detail)
  })
}
</script>
<style lang="css">
table .cell {
  padding: 0 !important;
}
</style>
